<template>
    <div class="h100 h-start-center w100 p-r">
        <a-spin :spinning="loading" class="p-center"></a-spin>
        <div class="tree-content h100 w20 p20">
            <div class="h-start-center">
                得分：
                <div class="red">{{ selfEvaluationScore }}（未加权）</div>
            </div>
            <div class="h-start-center">
                扣分：
                <div class="red">{{ deductEvaluationScore }}</div>
            </div>
            <div class="h-start-center">
                缺项分：
                <div class="red">{{ missEvaluationScore }}</div>
            </div>
            <a-tree
                v-if="treeData.length > 0"
                :replace-fields="{
                    key: 'templateId',
                }"
                :tree-data="treeData"
                show-icon
                default-expand-all
                @select="treeSelected"
                :selectedKeys="currentTreeNode"
            >
                <a-icon slot="switcherIcon" type="down" />
                <template slot="custom" slot-scope="{ ifRecord }">
                    <svg-icon
                        slot="custom"
                        icon-class="circle"
                        class="f8"
                        :class="ifRecord ? 'green' : 'gray'"
                    ></svg-icon>
                </template>
            </a-tree>
        </div>
        <div class="v-start-center h100 bg-white w80">
            <div class="table selfEvaluation pt10">
                <el-autocomplete
                    class="inline-input mb10"
                    v-model="searchValue"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入检索的三级项内容"
                    suffix-icon="el-icon-search"
                    @select="handleSelect"
                ></el-autocomplete>
                <a-table
                    bordered
                    v-if="tableData.length > 0"
                    rowKey="id"
                    :columns="columns"
                    :data-source="tableData"
                    @change="handleTableChange"
                    :key="tableKey"
                    :pagination="false"
                >
                    <template slot="zpMissItem" slot-scope="text, record">
                        <a-switch
                            :disabled="!isEdit"
                            v-model="record.zpMissItem"
                            @change="tableChange($event, record, 'zpMissItem')"
                        />
                    </template>
                    <template slot="zpScore" slot-scope="text, record">
                        <a-input-number
                            :disabled="!isEdit || record.zpMissItem || !record.file"
                            :value="text"
                            :min="0"
                            :max="record.score"
                            :step="0.1"
                            :precision="2"
                            @change="tableChange($event, record, 'zpScore')"
                        />
                    </template>
                    <template slot="file" slot-scope="text, record">
                        <a-upload
                            :disabled="!isEdit"
                            :before-upload="beforeUpload"
                            :action="uploadFileUrl"
                            name="file"
                            :multiple="true"
                            @change="uploadFileChange($event, record)"
                            :accept="fileType"
                            :default-file-list="record.file"
                            :headers="{
                                token: fileToken,
                            }"
                            @preview="previewFile"
                        >
                            <a-button>
                                <a-icon type="upload" />
                                上传pdf文件
                            </a-button>
                        </a-upload>
                    </template>
                    <template slot="zpRemarks" slot-scope="text, record">
                        <a-textarea
                            :autoSize="true"
                            :value="text"
                            placeholder="请输入"
                            @change="tableChange($event.target.value, record, 'zpRemarks')"
                        />
                    </template>
                </a-table>
            </div>
            <div class="h-end-center w100">
                <a-popconfirm title="当前数据已保存，是否返回列表" ok-text="是" cancel-text="否" @confirm="back">
                    <a-button :loading="loading" class="mr20" type="primary">返回列表</a-button>
                </a-popconfirm>
            </div>
        </div>
    </div>
</template>

<script>
import { getFileToken } from '@/common/api/common'
import url from '@/common/url-config.js'
import { selfEvaluationRecordApi, selfEvaluationApi } from '@/common/api/selfEvaluation'
import { debounce } from 'throttle-debounce'
let me
export default {
    props: {
        evaluationRecord: {
            required: true,
            type: Object,
        },
        isEdit: {
            default: true,
            type: Boolean,
        },
    },
    data() {
        return {
            searchValue: '',
            fileSrc: '',
            tableKey: +new Date(),
            fileType: '.pdf',
            uploadFileUrl: url.uploadFile,
            fileToken: '',
            originTreeData: [],
            columns1: [
                {
                    title: '三级项',
                    dataIndex: 'three',
                    customRender: (value, row, index) => {
                        const obj = {
                            children: value,
                            attrs: { rowSpan: row.rowSpan },
                        }

                        return obj
                    },
                },
                {
                    title: '评价内容',
                    dataIndex: 'four',
                    width: 220,
                },
                {
                    title: '评价操作指南',
                    dataIndex: 'operationGuide',
                    width: 300,
                },
            ],
            columns2: [
                {
                    title: '自评缺项',
                    dataIndex: 'zpMissItem',
                    scopedSlots: { customRender: 'zpMissItem' },
                    width: 80,
                },
            ],
            columns3: [
                {
                    title: '资料上传',
                    dataIndex: 'file',
                    align: 'center',
                    width: 170,
                    ellipsis: true,
                    scopedSlots: { customRender: 'file' },
                },
                {
                    title: '自评得分',
                    dataIndex: 'zpScore',
                    width: 120,
                    scopedSlots: { customRender: 'zpScore' },
                },
                {
                    title: '自评加/扣分原因',
                    dataIndex: 'zpRemarks',
                    scopedSlots: { customRender: 'zpRemarks' },
                },
            ],
            columns: [],
            loading: false,
            currentTreeNode: [],
            restaurants: [],
        }
    },
    mounted() {
        this.columns = [...this.columns1, ...this.columns2, ...this.columns3]
        me = this
    },
    destroyed() {
        me = null
    },
    watch: {
        evaluationRecord: {
            handler(obj) {
                this.getTemplate(obj.id)
            },
            immediate: true,
        },
    },
    computed: {
        selfEvaluationScore() {
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            let score = 0
            if (originArr.length > 0) {
                score = originArr.reduce((total, item) => {
                    let zpScore = item.zpScore || 0
                    return total + zpScore
                }, 0)
            }
            return score.toFixed(2)
        },
        missEvaluationScore() {
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            let missScore = 0
            if (originArr.length > 0) {
                missScore = originArr.reduce((total, item) => {
                    let score = 0
                    if (item.zpMissItem) {
                        score = item.score || 0
                    }
                    return total + score
                }, 0)
            }
            return missScore.toFixed(2)
        },
        deductEvaluationScore() {
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            let deductScore = 0
            if (originArr.length > 0) {
                deductScore = originArr.reduce((total, item) => {
                    let score = 0
                    // encourage鼓励项不参与减分
                    if (!item.zpMissItem && !item.encourage && item.zpArchiveJson) {
                        let zpScore = item.zpScore || 0
                        score = item.score - zpScore
                    }
                    return total + score
                }, 0)
            }
            return deductScore.toFixed(2)
        },
        tableData() {
            if (this.treeData.length < 0) {
                return []
            }
            let levelTwoId = this.currentTreeNode[0]
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            originArr = originArr.sort((a, b) => a.sortNum - b.sortNum)
            let threeArr = originArr.filter(item => item.level === 3 && item.parentId === levelTwoId)
            // 《--获得三级项的排序情况
            let threeSort = {}
            threeArr.forEach((item, index) => {
                threeSort[item.templateId] = index
            })
            // 获得三级项的排序情况--》
            let fourArr = originArr.filter(item => item.level === 4)

            fourArr = fourArr.filter(item => {
                item.fourSort = threeSort[item.parentId]
                let three = null
                for (let i = 0; i < threeArr.length; i++) {
                    if (threeArr[i].templateId === item.parentId) {
                        three = threeArr[i]
                        break
                    }
                }
                if (three) {
                    item.threeName = three.name
                    item.twoId = three.parentId
                    if (item.zpArchiveJson) {
                        item.file = JSON.parse(item.zpArchiveJson)
                    } else {
                        item.file = null
                    }
                    item.zpScore = item.zpScore ?? 0
                    return true
                }
                return false
            })
            fourArr = fourArr.sort((a, b) => a.fourSort - b.fourSort)
            let parentId = null
            let count = 0
            let startRow = null
            for (let i = 0; i < fourArr.length; i++) {
                let four = fourArr[i]
                if (parentId === four.parentId) {
                    four.rowSpan = 0
                    startRow.threeScore += four.score
                    count++
                } else {
                    startRow = four
                    startRow.threeScore = four.score
                    parentId = four.parentId
                    count = 1
                }
                startRow.rowSpan = count
            }
            fourArr.forEach(item => {
                item.four = `${item.name} (${item.score.toFixed(2)}分)`
                if (item.threeScore) {
                    item.three = `${item.threeName} (${item.threeScore.toFixed(2)}分)`
                }
            })
            return fourArr
        },
        treeData() {
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            originArr = originArr.sort((a, b) => a.sortNum - b.sortNum)
            let oneArr = originArr.filter(item => item.level === 1)
            let twoArr = originArr.filter(item => item.level === 2)
            let threeArr = originArr.filter(item => item.level === 3)
            let fourArr = originArr.filter(item => item.level === 4)
            fourArr.forEach(fourItem => {
                let zpScore = fourItem.zpScore || 0
                fourItem.ifRecord = !!(fourItem.zpMissItem || fourItem.zpArchiveJson)
                for (let i = 0; i < threeArr.length; i++) {
                    let threeItem = threeArr[i]
                    if (fourItem.parentId === threeItem.templateId) {
                        if (threeItem.zpScore !== null) {
                            threeItem.zpScore += zpScore
                            threeItem.ifRecord = threeItem.ifRecord || fourItem.ifRecord
                            threeItem.score += fourItem.score
                        } else {
                            threeItem.zpScore = zpScore
                            threeItem.ifRecord = fourItem.ifRecord
                            threeItem.score = fourItem.score
                        }
                        break
                    }
                }
            })
            threeArr.forEach(threeItem => {
                let zpScore = threeItem.zpScore || 0
                for (let i = 0; i < twoArr.length; i++) {
                    let twoItem = twoArr[i]
                    if (threeItem.parentId === twoItem.templateId) {
                        if (twoItem.zpScore !== null) {
                            twoItem.zpScore += zpScore
                            twoItem.score += threeItem.score
                            twoItem.ifRecord = twoItem.ifRecord || threeItem.ifRecord
                        } else {
                            twoItem.zpScore = zpScore
                            twoItem.score = threeItem.score
                            twoItem.ifRecord = threeItem.ifRecord
                        }
                        break
                    }
                }
            })
            twoArr.forEach(twoItem => {
                let zpScore = twoItem.zpScore || 0

                twoItem.zpScore = +(Math.round(zpScore * 100) / 100).toFixed(2)
                twoItem.score = +(Math.round(twoItem.score * 100) / 100).toFixed(2)
                twoItem.title = `${twoItem.name}(${zpScore}/${twoItem.score})分`
                twoItem.scopedSlots = {
                    icon: 'custom',
                }
                for (let i = 0; i < oneArr.length; i++) {
                    let oneItem = oneArr[i]
                    if (twoItem.parentId === oneItem.templateId) {
                        if (oneItem.zpScore !== null) {
                            oneItem.zpScore += zpScore
                            oneItem.score += twoItem.score
                            oneItem.ifRecord = oneItem.ifRecord || twoItem.ifRecord
                            oneItem.children.push(twoItem)
                        } else {
                            oneItem.zpScore = zpScore
                            oneItem.score = twoItem.score
                            oneItem.ifRecord = twoItem.ifRecord
                            oneItem.children = [twoItem]
                        }
                        break
                    }
                }
            })
            oneArr.forEach(item => {
                let zpScore = item.zpScore || 0
                item.selectable = false //一级节点禁止选择
                item.zpScore = +(Math.round(zpScore * 100) / 100).toFixed(2)
                item.score = +(Math.round(item.score * 100) / 100).toFixed(2)
                item.title = `${item.name}(${zpScore}/${item.score})分`
                item.scopedSlots = {
                    icon: 'custom',
                }
            })
            if (this.currentTreeNode.length <= 0 && oneArr[0]?.children[0]?.templateId) {
                // eslint-disable-next-line vue/no-side-effects-in-computed-properties
                this.currentTreeNode = [oneArr[0]?.children[0]?.templateId] || []
            }
            return oneArr
        },
    },
    methods: {
        initRestaurants() {
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            let threeArr = originArr.filter(item => item.level === 3)
            threeArr.forEach(item => {
                item.value = item.name
            })
            this.restaurants = threeArr
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
            // 调用 callback 返回建议列表的数据
            cb(results)
        },
        createFilter(queryString) {
            return restaurant => {
                return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
            }
        },
        handleSelect(item) {
            this.currentTreeNode = [item.parentId]
        },
        uploadFileChange(info, record) {
            const { id } = record
            let fileList = [...info.fileList]
            if (fileList.length > 0) {
                let len = fileList.length
                let doneCount = 0
                fileList.forEach(file => {
                    if (file.status === 'done') {
                        doneCount++
                        if (file.response) {
                            file.fileId = file.response.data.id
                            file.uid = file.fileId
                            file.url = file.fileId // 给file赋url字体才能变蓝
                        }
                    }

                    if (file.status === 'error') {
                        if (file.response.errorCode === 401) {
                            this.$notification401(file.response.message)
                        }
                        file.response = file.response.message || '服务器异常'
                    }
                })
                //数量相等表示所有文件上传完成
                if (doneCount === len) {
                    let simpleFileList = fileList.map(file => {
                        const { uid, name, status, url } = file
                        return {
                            uid,
                            name,
                            status,
                            url,
                        }
                    })
                    simpleFileList = JSON.stringify(simpleFileList)
                    this.tableChange(simpleFileList, record, 'zpArchiveJson')
                }
            } else {
                // this.tableChange('', id, 'zpArchiveId')
                this.tableChange('', record, 'zpArchiveJson')
                this.tableChange(0, record, 'zpScore')
                this.$message.warning('请上传文件并重新打分')
            }
        },

        previewFile(file) {
            let { uid: fileId, name: fileName } = file
            let fileType = 'pdf'
            const fileSrc = `/file/api/Preview/v1/${fileId}`
            if (fileType === 'pdf') {
                this.fileSrc = `/pdfjs-2.6.347-dist/web/viewer.html?file=${fileSrc}&saveName=${fileName}`
            } else if (fileType === 'other') {
                this.fileSrc = `https://view.officeapps.live.com/op/embed.aspx?src=https://api-file.scdem.cn/api/Preview/v1/${fileId}`
            } else {
                this.fileSrc = fileSrc
            }
            let routeUrl = this.$router.resolve({
                path: '/preview',
                query: { fileSrc: this.fileSrc },
            })
            window.open(routeUrl.href, '_blank')
        },
        async getTemplate(id) {
            this.loading = true
            try {
                let res = await selfEvaluationApi.get({ id })
                let evaluationList = res?.data?.evaluationList || []
                this.originTreeData = evaluationList.sort((a, b) => a?.sortNum - b?.sortNum)
                this.initRestaurants()
            } catch (e) {
                console.log(e)
            }
            this.loading = false
        },
        async getDetails() {
            let loading = this.$loading()
            try {
                let res = await selfEvaluationApi.recordDetails({ id: this.evaluationRecord.id })
                console.log(res)
            } catch (e) {
                console.log(e)
            }
            loading.close()
        },
        back() {
            this.$emit('typeChange', 'table')
        },
        save() {
            this.$emit('save')
        },
        async beforeUpload(file) {
            if (file?.size >= 100 * 1024 * 1024) {
                this.$message.error(file.name + '文件大于100M，上传失败！')
                return Promise.reject()
            } else {
                try {
                    let res = await getFileToken()
                    this.fileToken = res?.data?.token
                } catch (e) {
                    console.log(e)
                }
            }
        },
        tableChange(value, record, key) {
            const { id, threeName } = record
            console.log(value, id, key)
            let row = null
            let rowIndex = null
            for (let i = 0; i < this.originTreeData.length; i++) {
                let currentRow = this.originTreeData[i]
                if (currentRow.id === id) {
                    row = { ...currentRow }
                    rowIndex = i
                    break
                }
            }
            if (row) {
                row[key] = value
                if (key === 'zpMissItem') {
                    row.zpScore = 0
                } else if (key === 'zpScore') {
                    if (typeof value !== 'number') {
                        return
                    }
                    if (value > row.score) {
                        this.$message.error('输入分值超过当前得分上限，将自动调整为' + row.score + '分')
                        row[key] = row.score
                    }
                }

                this.$set(this.originTreeData, rowIndex, row)
                this.putChange(id)
            }
        },
        treeSelected(selectedKeys, obj) {
            this.currentTreeNode = selectedKeys
            let node = null
            for (let i = 0; i < this.originTreeData.length; i++) {
                let item = this.originTreeData[i]
                if (item.templateId === selectedKeys[0]) {
                    node = item
                    break
                }
            }
            if (node?.encourage) {
                this.columns = [...this.columns1, ...this.columns3]
            } else {
                this.columns = [...this.columns1, ...this.columns2, ...this.columns3]
            }
        },
        handleTableChange() {
            this.getTableData()
        },
        getTableData() {
            return false
        },
        putChange: debounce(100, false, id => {
            // 通过id获取到最新的行数据
            let record = me.tableData.filter(item => item.id === id)[0] || {}
            const { zpMissItem, zpScore, zpArchiveJson, zpRemarks } = record
            let params = {
                templateRecordId: id,
                zpArchiveJson,
                zpRemarks,
                zpMissItem: zpMissItem,
                zpScore,
            }

            //静默保存
            selfEvaluationRecordApi.zp(params)
        }),
    },
}
</script>

<style lang="scss" scoped>
.tab-box {
    height: calc(100vh - 370px);
    overflow-y: auto;
}
.file-content {
    height: 835px;
    &_header {
        border-bottom: 1px solid #d5d8de;
        padding: 32px 32px 0 32px;
        h1 {
            font-size: 24px;
            font-family: AlibabaPuHuiTiM, AlibabaPuHuiTiM-Regular;
            font-weight: 400;
            color: #243144;
            text-align: center;
        }
        .header-bot {
            font-size: 14px;
            font-family: AlibabaPuHuiTiR, AlibabaPuHuiTiR-Regular;
            font-weight: 400;
            color: rgba(36, 49, 68, 0.8);
            margin: 24px 0;
        }
    }
    &_content {
        padding: 32px;
        overflow-y: auto;
        height: calc(100% - 138px);
        /deep/ .ant-back-top {
            bottom: 380px;
        }
    }
}
</style>
